package com.xiaomazi.oss.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.UUID;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.xiaomazi.common.utils.R;
import com.xiaomazi.oss.config.OSSEntityConfiguration;
import com.xiaomazi.oss.service.OssService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;

/**
 * @program: llxy-parent
 * @description: 阿里云服务业务实现类
 * @author: 小马子
 * @create: 2023-02-14 15:03
 **/
@Service
public class OssServiceImpl implements OssService {

    @Autowired
    private OSSEntityConfiguration oss;

    /**
     * 上传讲师头像
     * @param file 上传的文件
     * @return url
     */
    @Override
    public R uploadTeacherAvatar(MultipartFile file) {
        OSS ossClient = null;
        String endpoint = oss.getEndpoint();
        String keyId = oss.getKeyId();
        String keySecret = oss.getKeySecret();
        String bucketName = oss.getBucketName();
        try {
            ossClient = new OSSClientBuilder().build(endpoint, keyId, keySecret);
            String path = DateUtil.format(new Date(), "yyyy/MM/dd");
            path = path + "/" + UUID.fastUUID().toString(true) + file.getOriginalFilename();
            ossClient.putObject(bucketName,path,file.getInputStream());
            return R.ok().data("url","https://"+bucketName+"."+endpoint+"/"+path);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (null != ossClient){
                ossClient.shutdown();
            }
        }
    }
}
